<template>
  <div ref="homeRef" class="m-home">
    <div v-for="item in indicatorListFilter" :key="item.value">
      <component
        :is="item.component"
        :index="activeIndex"
        :data="item.data"
        :id="'m-page-' + item.value"
        class="m-page-section"
      />
    </div>

    <div class="m-home-indicator">
      <div
        v-for="item in indicatorListFilter"
        :key="item.value"
        class="m-indicator-item"
        @click="setActiveItem(item.value)"
      >
        <div v-if="item.value === activeIndex" class="m-indicator-label">
          {{ item.label }}
        </div>
        <div class="m-indicator-icon">
          <img v-if="item.value === activeIndex" src="@/assets/logo.png" />
          <div v-else class="m-dot" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getCarouselList, homeDataList, cooperateList } from "@/api/home";
import { serviceList } from "@/api/product";
import { solutionList } from "@/api/scheme";
import { productList } from "@/api/ecology";
import { staffList } from "@/api/about";

import Banner1 from "@/views/mobile/home/components/Banner1.vue";
import Banner2 from "@/views/mobile/home/components/Banner2.vue";
import Banner3 from "@/views/mobile/home/components/Banner3.vue";
import Banner4 from "@/views/mobile/home/components/Banner4.vue";
import Banner5 from "@/views/mobile/home/components/Banner5.vue";
import Banner6 from "@/views/mobile/home/components/Banner6.vue";
import Banner7 from "@/views/mobile/home/components/Banner7.vue";

const activeIndex = ref<number>(0);
const indicatorList = ref<Array<any>>([
  { value: 0, label: "业务展示", component: markRaw(Banner1), data: null },
  { value: 1, label: "关于天启明通", component: markRaw(Banner2), data: null },
  { value: 2, label: "", component: markRaw(Banner3), data: null },
  { value: 3, label: "", component: markRaw(Banner4), data: null },
  { value: 4, label: "生态产品", component: markRaw(Banner5), data: null },
  { value: 5, label: "团队介绍", component: markRaw(Banner6), data: null },
  { value: 6, label: "合作伙伴", component: markRaw(Banner7), data: null },
]);

const indicatorListFilter = computed(() => {
  return indicatorList.value.filter((item) => item.data);
});

const homeRef = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;
let observedIds = new Set<string>();
let lastScrollTime = 0;
let touchStartY = 0;

onMounted(() => {
  // 获取Banner1数据
  getCarousel();
  // 获取Banner2数据
  getHomeDataList();
  // 获取Banner3数据
  getService();
  // 获取Banner4数据
  getSolution();
  // 获取Banner5数据
  getProductList();
  // 获取Banner6数据
  getStaffList();
  // 获取Banner7数据
  getCooperateList();

  initIntersectionObserver();
  // 初始监听（首屏可能只有部分数据渲染完成）
  observeSections();
  // 触摸事件（移动端整屏滑动）
  homeRef.value?.addEventListener("touchstart", handleTouchStart, { passive: true });
  homeRef.value?.addEventListener("touchend", handleTouchEnd, { passive: true });
});

const initIntersectionObserver = () => {
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
          const id = entry.target.id.replace("m-page-", "");
          const newIndex = parseInt(id);
          if (!isNaN(newIndex) && newIndex !== activeIndex.value) {
            activeIndex.value = newIndex;
          }
        }
      });
    },
    { threshold: [0, 0.5, 1], root: null, rootMargin: "0px" }
  );
};

// 监听并绑定当前已渲染的区块
const observeSections = () => {
  if (!observer) return;
  document.querySelectorAll(".m-page-section").forEach((section) => {
    const id = (section as HTMLElement).id;
    if (!observedIds.has(id)) {
      observer?.observe(section);
      observedIds.add(id);
    }
  });
};

// 当可渲染的区块列表变化（数据加载完成）时，补充观察新出现的区块
watch(
  () => indicatorListFilter.value.map((i) => i.value),
  () => {
    nextTick(() => {
      observeSections();
    });
  },
  { flush: "post" }
);

const setActiveItem = (index: number) => {
  // 检查目标组件是否存在（有数据）
  const targetItem = indicatorList.value.find((item) => item.value === index);
  if (!targetItem || !targetItem.data) {
    return;
  }

  const el = document.getElementById("m-page-" + index) as HTMLElement | null;
  if (el) {
    el.scrollIntoView({ block: "start", behavior: "smooth" });
    setTimeout(() => {
      activeIndex.value = index;
    }, 300);
  }
};

// 获取轮播图
const getCarousel = () => {
  getCarouselList({ pageNum: 1, pageSize: 100, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[0].data = res.rows;
    }
  });
};

// 获取数据展示列表
const getHomeDataList = () => {
  homeDataList({ pageNum: 1, pageSize: 4, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[1].data = res.rows;
    }
  });
};

// 获取产品服务
const getService = () => {
  serviceList({ displayHome: 1, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[2].data = res.rows[0];
      indicatorList.value[2].label = res.rows[0].name;
    }
  });
};

// 获取解决方案
const getSolution = () => {
  solutionList({ displayHome: 1, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[3].data = res.rows[0];
      indicatorList.value[3].label = res.rows[0].name;
    }
  });
};

// 获取生态产品列表
const getProductList = () => {
  productList({
    pageNum: 1,
    pageSize: 8,
    status: 0,
    displayHome: 1,
  }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      let list = res.rows.map((item: any) => {
        return {
          ...item,
          cover: item.image ? item.image?.split(",")[0] : "",
        };
      });
      indicatorList.value[4].data = [];
      for (let i = 0; i < list.length / 4; i++) {
        let arr = list.slice(i * 4, (i + 1) * 4);
        indicatorList.value[4].data.push(arr);
      }
    }
  });
};

// 获取团队介绍列表
const getStaffList = () => {
  staffList({ pageNum: 1, pageSize: 4, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[5].data = res.rows;
    }
  });
};

// 获取合作伙伴列表
const getCooperateList = () => {
  cooperateList({ pageNum: 1, pageSize: 32, status: 0 }).then((res: any) => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      indicatorList.value[6].data = res.rows;
    }
  });
};

onUnmounted(() => {
  observer?.disconnect();
  observedIds.clear();
  homeRef.value?.removeEventListener("touchstart", handleTouchStart as any);
  homeRef.value?.removeEventListener("touchend", handleTouchEnd as any);
});

// 触摸滑动处理，判断方向并整屏跳转
const handleTouchStart = (e: TouchEvent) => {
  if (e.touches && e.touches.length > 0) {
    touchStartY = e.touches[0].clientY;
  }
};

const handleTouchEnd = (e: TouchEvent) => {
  const now = Date.now();
  if (now - lastScrollTime < 300) return;
  lastScrollTime = now;

  const endY = (e.changedTouches && e.changedTouches[0]?.clientY) || touchStartY;
  const deltaY = endY - touchStartY; // 正值表示向下滑（返回上一屏）

  const availableIndices = indicatorListFilter.value.map((item) => item.value);
  const currentIndex = availableIndices.indexOf(activeIndex.value);
  if (currentIndex === -1) return;

  // 设置触发阈值，避免轻微滑动就跳屏
  const threshold = 50;
  let targetIndex = activeIndex.value;

  if (Math.abs(deltaY) >= threshold) {
    if (deltaY > 0 && currentIndex > 0) {
      // 向下滑，上一屏
      targetIndex = availableIndices[currentIndex - 1];
    } else if (deltaY < 0 && currentIndex < availableIndices.length - 1) {
      // 向上滑，下一屏
      targetIndex = availableIndices[currentIndex + 1];
    }
  }

  if (targetIndex !== activeIndex.value) {
    setActiveItem(targetIndex);
  }
};
</script>
<style lang="scss" scoped>
.m-home {
  position: relative;
  scroll-behavior: smooth;
}

.m-home-indicator {
  position: fixed;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 999;
  display: flex;
  flex-direction: column;
}

.m-indicator-item {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 30px;
}

.m-indicator-label {
  font-size: 12px;
  color: #fff;
  line-height: 14px;
  margin-right: 8px;
  max-width: 160px;
}

.m-indicator-icon {
  width: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  img {
    width: 16px;
    height: 16px;
  }
}

.m-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
}

// 区块对齐整屏
.m-page-section {
  scroll-snap-align: start;
}
</style>
